package com.intel.service.Impl;

import com.intel.mapper.DictionaryMapper;
import com.intel.mapper.MedicineMapper;
import com.intel.model.YmCMedicine;
import com.intel.model.YmSDic;
import com.intel.service.UploadService;
import com.mchz.mdmp.model.Resume;
import com.mchz.mdmp.webservice.MasterDataWebService;
import lombok.extern.slf4j.Slf4j;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hduprince on 17/10/14.
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${wsdlUrl}")
    private String wsdlUrl;

    @Resource
    private MedicineMapper medicineMapper;

    @Resource
    private DictionaryMapper dictionaryMapper;

    private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");
    private static OMFactory fac = OMAbstractFactory.getOMFactory();

    private void uploadYmCMedicine(String token, YmCMedicine ymCMedicine, String type, String orgCode) {
        //根节点 UPLOAD
        OMElement upload = fac.createOMElement("UPLOAD", null);

        //一级子节点 TOKEN
        OMElement tokenElement = fac.createOMElement("TOKEN", null);
        tokenElement.setText(token);
        upload.addChild(tokenElement);

        //一级子节点 MEDICINESWAPINFOS/MAKEUPSWAPINFOS/INSTRUMENTSWAPINFOS
        String nodeName = "";
        if("medicine".equals(type)) {
            nodeName = "MEDICINESWAPINFOS";
        } else if ("makeup".equals(type)) {
            nodeName = "MAKEUPSWAPINFOS";
        } else if ("instrument".equals(type)) {
            nodeName = "INSTRUMENTSWAPINFOS";
        } else {
            return;
        }
        OMElement firstClassNode = fac.createOMElement(nodeName, null);

        //二级子节点 MEDICINESWAPINFO/MAKEUPSWAPINFO/INSTRUMENTSWAPINFO
        if("medicine".equals(type)) {
            firstClassNode.addChild(medicineXmlConvert(ymCMedicine));
        } else if ("makeup".equals(type)) {
            firstClassNode.addChild(makeupXmlConvert(ymCMedicine));
        } else if ("instrument".equals(type)) {
            firstClassNode.addChild(instrumentXmlConvert(ymCMedicine));
        } else {
            return;
        }
        upload.addChild(firstClassNode);

        //上传接口
        String response = invokeSoapWsUpload(writeFile(upload.toString(), "medicine", orgCode, token));

        Pattern p = Pattern.compile("<result>(.*)</result>");
        Matcher m = p.matcher(response);

        //日志输出上传商品信息和返回结果
        log.info(type + ymCMedicine.getId() + ymCMedicine.getName());
        log.info(response);

        //根据返回结果更新状态
        if(response.contains("成功")) {
            String resultSeq;
            while (m.find()) {
                resultSeq = m.group(1);
                log.info(resultSeq);
                ymCMedicine.setResultSeq(resultSeq);
            }
            if(ymCMedicine.getResultSeq() != null || !"".equals(ymCMedicine.getResultSeq()))
                medicineMapper.updateResultSeq(ymCMedicine);
            else
                log.error("resultSeq为空 1");
        } else {
            ymCMedicine.setUploadStatus("5");
            medicineMapper.updateUploadStatus(ymCMedicine);
        }
    }

    public void uploadOneByOne(String orgCode, String token) {
        //查询出要上传的商品列表
        List<YmCMedicine> list = medicineMapper.getYmCMedicineListLastDay(orgCode);
        if (list.size() != 0) {
            for (YmCMedicine ymCMedicine : list) {
                //判断商品的类型
                if ("化学药".equals(ymCMedicine.getMedicType()) || "中成药".equals(ymCMedicine.getMedicType()) || "中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
                    uploadYmCMedicine(token, ymCMedicine, "medicine", orgCode);
                } else if ("非药品".equals(ymCMedicine.getMedicType()) && "化妆品".equals(ymCMedicine.getOtcCode())) {
                    uploadYmCMedicine(token, ymCMedicine, "makeup", orgCode);
                } else if ("医疗器械".equals(ymCMedicine.getMedicType())) {
                    uploadYmCMedicine(token, ymCMedicine, "instrument", orgCode);
                } else {
                    ymCMedicine.setUploadStatus("5");
                    medicineMapper.updateUploadStatus(ymCMedicine);
                }
            }
        }
    }

    public void executeFeedBackStatus(String orgCode) {
        List<YmCMedicine> list = medicineMapper.getYmCMedicineListForUploadStatus(orgCode);
        if(list != null || list.size() != 0) {
            for(YmCMedicine ymCMedicine : list) {
                changeFeedBackStatus(ymCMedicine);
            }
        }
    }

    private void changeFeedBackStatus(YmCMedicine ymCMedicine) {
        String resultSeq = ymCMedicine.getResultSeq();
        if(resultSeq != null || !"".equals(resultSeq)) {
            String feedBackResponse = invokeSoapWsFeedback(feedbackXmlConvert(ymCMedicine.getResultSeq()).toString());
            log.info(feedBackResponse);
            if(feedBackResponse.contains("数据审核中")) {
                ymCMedicine.setUploadStatus("1");
                medicineMapper.updateUploadStatus(ymCMedicine);
            } else if(feedBackResponse.contains("审批结束成功入库")) {
                ymCMedicine.setUploadStatus("2");
                medicineMapper.updateUploadStatus(ymCMedicine);
            } else if(feedBackResponse.contains("数据未被采纳-采用了其他数据")) {
                ymCMedicine.setUploadStatus("3");
                medicineMapper.updateUploadStatus(ymCMedicine);
            } else if(feedBackResponse.contains("库内已存在这条数据")) {
                ymCMedicine.setUploadStatus("4");
                medicineMapper.updateUploadStatus(ymCMedicine);
            } else if(feedBackResponse.contains("重复插入数据")) {
                log.info("重复插入数据");
            } else {
                ymCMedicine.setUploadStatus("5");
                medicineMapper.updateUploadStatus(ymCMedicine);
            }
        } else {
            log.error("resultSeq为空 2");
        }

    }

    public void upload(String orgCode, String token) {
        //从药盟库根据orgCode查询出要上传的商品列表，最后上传时间这个条件直接写在sql里
        List<YmCMedicine> list = medicineMapper.getYmCMedicineListLastDay(orgCode);
        if(list.size() != 0) {

            OMElement token1 = fac.createOMElement("TOKEN", null);
            token1.setText(token);

            OMElement token3 = fac.createOMElement("TOKEN", null);
            token3.setText(token);

            OMElement token4 = fac.createOMElement("TOKEN", null);
            token4.setText(token);

            //药品报文
            OMElement upload1 = fac.createOMElement("UPLOAD", null);
            upload1.addChild(token1);
            //化妆品报文
            OMElement upload3 = fac.createOMElement("UPLOAD", null);
            upload3.addChild(token3);
            //医疗器械报文
            OMElement upload4 = fac.createOMElement("UPLOAD", null);
            upload4.addChild(token4);

            //药品
            OMElement medicineswapinfos = fac.createOMElement("MEDICINESWAPINFOS", null);
            int numOfmedicine = 0;
            //化妆品
            OMElement makeupswapinfo = fac.createOMElement("MAKEUPSWAPINFOS", null);
            int numOfmakeup = 0;
            //医疗器械
            OMElement instrumentswapinfos = fac.createOMElement("INSTRUMENTSWAPINFOS", null);
            int numOfinstrument = 0;

            for (YmCMedicine ymCMedicine : list) {
                if ("化学药".equals(ymCMedicine.getMedicType()) || "中成药".equals(ymCMedicine.getMedicType()) || "中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
                    medicineswapinfos.addChild(medicineXmlConvert(ymCMedicine));
                    numOfmedicine++;
                } else if ("非药品".equals(ymCMedicine.getMedicType()) && "化妆品".equals(ymCMedicine.getOtcCode())) {
                    makeupswapinfo.addChild(makeupXmlConvert(ymCMedicine));
                    numOfmakeup++;
                } else if ("医疗器械".equals(ymCMedicine.getMedicType())) {
                    instrumentswapinfos.addChild(instrumentXmlConvert(ymCMedicine));
                    numOfinstrument++;
                }
            }


            if (medicineswapinfos.getFirstElement() != null) {
                log.info(String.valueOf(numOfmedicine));
                upload1.addChild(medicineswapinfos);
                String response = invokeSoapWsUpload(writeFile(upload1.toString(), "medicine", orgCode, token));
                System.out.println(response);
                if (response.contains("成功")) {
                    log.info(response);
                }
                else {
                    log.error(response);
                    log.error(orgCode + df.format(new Date()) + "药品上传失败");
                }
            }
            if (makeupswapinfo.getFirstElement() != null) {
                log.info(String.valueOf(numOfmakeup));
                upload3.addChild(makeupswapinfo);
                String response = invokeSoapWsUpload(writeFile(upload3.toString(), "makeup", orgCode, token));
                if (response.contains("成功")) {
                    log.info(response);
                }
                else {
                    log.error(response);
                    log.error(orgCode + df.format(new Date()) + "化妆品上传失败");
                }
            }
            if (instrumentswapinfos.getFirstElement() != null) {
                log.info(String.valueOf(numOfinstrument));
                upload4.addChild(instrumentswapinfos);
                String response = invokeSoapWsUpload(writeFile(upload4.toString(), "instrument", orgCode, token));
                if (response.contains("成功")) {
                    log.info(response);
                }
                else {
                    log.error(response);
                    log.error(orgCode + df.format(new Date()) + "医疗器械上传失败");
                }
            }
        }
    }

    public void uploadAll(String orgCode, String token) {
        List<YmCMedicine> list = medicineMapper.getYmCMedicineListAll(orgCode);
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMElement token1 = fac.createOMElement("TOKEN", null);
        token1.setText(token);

        OMElement token3 = fac.createOMElement("TOKEN", null);
        token3.setText(token);

        OMElement token4 = fac.createOMElement("TOKEN", null);
        token4.setText(token);

        //药品报文
        OMElement upload1 = fac.createOMElement("UPLOAD", null);
        upload1.addChild(token1);
        //化妆品报文
        OMElement upload3 = fac.createOMElement("UPLOAD", null);
        upload3.addChild(token3);
        //医疗器械报文
        OMElement upload4 = fac.createOMElement("UPLOAD", null);
        upload4.addChild(token4);

        //药品
        OMElement medicineswapinfos = fac.createOMElement("MEDICINESWAPINFOS", null);
        int numOfmedicine = 0;
        int parts1 = 0;
        //化妆品
        OMElement makeupswapinfo = fac.createOMElement("MAKEUPSWAPINFO", null);
        int numOfmakeup = 0;
        int parts3 = 0;
        //医疗器械
        OMElement instrumentswapinfos = fac.createOMElement("INSTRUMENTSWAPINFOS", null);
        int numOfinstrument = 0;
        int parts4 = 0;

        for(YmCMedicine ymCMedicine : list){
            if("化学药".equals(ymCMedicine.getMedicType()) || "中成药".equals(ymCMedicine.getMedicType()) || "中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
                medicineswapinfos.addChild(medicineXmlConvert(ymCMedicine));
                numOfmedicine++;
                if(numOfmedicine > 99) {
                    parts1++;
                    uploadXml(upload1, medicineswapinfos, numOfmedicine, orgCode, "medicine", parts1, token);
                    numOfmedicine = 0;
                    medicineswapinfos.discard();
                    medicineswapinfos = fac.createOMElement("MEDICINESWAPINFOS", null);
                }
            }
            else if("非药品".equals(ymCMedicine.getMedicType()) && "化妆品".equals(ymCMedicine.getOtcCode())){
                makeupswapinfo.addChild(makeupXmlConvert(ymCMedicine));
                numOfmakeup++;
                if(numOfmakeup > 99) {
                    parts3++;
                    uploadXml(upload3, makeupswapinfo, numOfmakeup, orgCode, "makeup", parts3, token);
                    numOfmakeup = 0;
                    makeupswapinfo.discard();
                    makeupswapinfo = fac.createOMElement("MAKEUPSWAPINFO", null);
                }
            }
            else if("医疗器械".equals(ymCMedicine.getMedicType())){
                instrumentswapinfos.addChild(instrumentXmlConvert(ymCMedicine));
                numOfinstrument++;
                if(numOfinstrument > 99) {
                    parts4++;
                    uploadXml(upload4, instrumentswapinfos, numOfinstrument, orgCode, "instrument", parts4, token);
                    numOfinstrument = 0;
                    instrumentswapinfos.discard();
                    instrumentswapinfos = fac.createOMElement("INSTRUMENTSWAPINFOS", null);
                }
            }
        };

        uploadXml(upload1, medicineswapinfos, numOfmedicine, orgCode,"medicine", ++parts1, token);
        uploadXml(upload3, makeupswapinfo, numOfmakeup, orgCode,"makeup", ++parts3, token);
        uploadXml(upload4, instrumentswapinfos, numOfinstrument, orgCode,"instrument", ++parts4, token);

    }

    private OMElement medicineXmlConvert(YmCMedicine ymCMedicine) {
        OMElement medicineswapinfo = fac.createOMElement("MEDICINESWAPINFO", null);
        OMElement product_code = fac.createOMElement("PRODUCT_CODE", null);
        OMElement product_name = fac.createOMElement("PRODUCT_NAME", null);
        OMElement trade_name = fac.createOMElement("TRADE_NAME", null);
        OMElement approval_number = fac.createOMElement("APPROVAL_NUMBER", null);
        OMElement spec = fac.createOMElement("SPEC", null);
        OMElement type = fac.createOMElement("TYPE", null);
        OMElement corp_name = fac.createOMElement("CORP_NAME", null);
        OMElement is_import = fac.createOMElement("IS_IMPORT", null);
        OMElement import_register_number = fac.createOMElement("IMPORT_REGISTER_NUMBER", null);
        OMElement branch = fac.createOMElement("BRANCH", null);
        OMElement useful_life = fac.createOMElement("USEFUL_LIFE", null);
        OMElement first_code = fac.createOMElement("FIRST_CODE", null);
        OMElement sec_code = fac.createOMElement("SEC_CODE", null);
        OMElement classification_efficacy = fac.createOMElement("CLASSIFICATION_EFFICACY", null);
        OMElement pack_spec = fac.createOMElement("PACK_SPEC", null);
        OMElement base_unit = fac.createOMElement("BASE_UNIT", null);
        OMElement is_ephedrine = fac.createOMElement("IS_EPHEDRINE", null);
        OMElement storage_condition = fac.createOMElement("STORAGE_CONDITION", null);
        OMElement prod_place = fac.createOMElement("PROD_PLACE", null);
        OMElement english_name = fac.createOMElement("ENGLISH_NAME", null);
        OMElement scope_business = fac.createOMElement("SCOPE_BUSINESS", null);
        OMElement status = fac.createOMElement("STATUS", null);
        OMElement is_old = fac.createOMElement("IS_OLD", null);
        OMElement is_exc = fac.createOMElement("IS_EXC", null);

        OMElement license_period = fac.createOMElement("B_EFFECTIVE_NAME", null);

        product_code.setText(String.valueOf(ymCMedicine.getId()));
        medicineswapinfo.addChild(product_code);

        //通用名称
        if(ymCMedicine.getDefaultName().indexOf('#') == 0) {
            product_name.setText(ymCMedicine.getDefaultName().substring(1));
            medicineswapinfo.addChild(product_name);
        } else {
            product_name.setText(ymCMedicine.getDefaultName());
            medicineswapinfo.addChild(product_name);
        }

        //商品名
        if(ymCMedicine.getName().indexOf('#') == 0) {
            trade_name.setText(ymCMedicine.getName().substring(1));
            medicineswapinfo.addChild(trade_name);
        } else {
            trade_name.setText(ymCMedicine.getName());
            medicineswapinfo.addChild(trade_name);
        }

        //批准文号和进口注册证号
        if("0".equals(ymCMedicine.getIsImport()) || ymCMedicine.getIsImport() == null) {
            //非进口药品要填批准文号
            approval_number.setText(ymCMedicine.getLicenseNumber());
            medicineswapinfo.addChild(approval_number);
        } else if("1".equals(ymCMedicine.getIsImport())) {
            //进口药品要填进口注册证号
            import_register_number.setText(ymCMedicine.getImportRegeditId());
            medicineswapinfo.addChild(import_register_number);
        }

        //批准文号有效期
        if(ymCMedicine.getLicensePeriod() != null) {
            license_period.setText(ymCMedicine.getLicensePeriod());
            medicineswapinfo.addChild(license_period);
        }

        //规格
        spec.setText(ymCMedicine.getStandard());
        medicineswapinfo.addChild(spec);

        //剂型
        if(ymCMedicine.getDosageId() == null) {
            type.setText("其他");
        } else {
            type.setText(ymCMedicine.getDosageId());
        }
        medicineswapinfo.addChild(type);

        //生产企业
        corp_name.setText(ymCMedicine.getFacName());
        medicineswapinfo.addChild(corp_name);

        //是否为进口产品
        is_import.setText(ymCMedicine.getIsImport());
        medicineswapinfo.addChild(is_import);

        //分包装企业名称
        branch.setText(ymCMedicine.getFacName());
        medicineswapinfo.addChild(branch);

        //有效期（月）
        useful_life.setText(ymCMedicine.getPeriod());
        medicineswapinfo.addChild(useful_life);

        //一级分类 附1.1
        if("化学药".equals(ymCMedicine.getMedicType()) || "中成药".equals(ymCMedicine.getMedicType()) || "中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
            first_code.setText("10");
        }
        else if("非药品".equals(ymCMedicine.getMedicType()) && ("化妆品".equals(ymCMedicine.getOtcCode()))) {
            first_code.setText("20");
        }
        else if("医疗器械".equals(ymCMedicine.getMedicType())) {
            first_code.setText("30");
        }
        else if("保健食品".equals(ymCMedicine.getMedicType())) {
            first_code.setText("40");
        }

        medicineswapinfo.addChild(first_code);

        //二级分类 附1.2
        if("化学药".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("1005");
        }
        else if("中成药".equals(ymCMedicine.getMedicType()) ) {
            sec_code.setText("1003");
        }
        else if("中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("1001");
        }
        else if("保健食品".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("4027");
        }
        else if("非药品".equals(ymCMedicine.getMedicType()) && ("化妆品".equals(ymCMedicine.getOtcCode()))) {
            sec_code.setText("2001");
        }
        else if("医疗器械".equals(ymCMedicine.getMedicType())) {
            if("一类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("3001");
            } else if ("二类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("3002");
            } else if ("三类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("3003");
            } else {
                sec_code.setText("3001");
            }
        }

        medicineswapinfo.addChild(sec_code);

        //三级分类 附1.3
        if(ymCMedicine.getSortCode() == null) {
            classification_efficacy.setText("其他");
        } else {
            classification_efficacy.setText(ymCMedicine.getSortCode());
        }

        medicineswapinfo.addChild(classification_efficacy);


        //包装规格
        pack_spec.setText(ymCMedicine.getStandard());
        medicineswapinfo.addChild(pack_spec);

        //单位 附1.4
        if(ymCMedicine.getBaseUnit() == null) {
            base_unit.setText("其他");
        } else {
            base_unit.setText(ymCMedicine.getBaseUnit());
        }
        medicineswapinfo.addChild(base_unit);

        //是否为麻黄碱
        is_ephedrine.setText(ymCMedicine.getIsEphedrine());
        medicineswapinfo.addChild(is_ephedrine);

        if(ymCMedicine.getStoragesortCodeValue() != null) {
            storage_condition.setText(ymCMedicine.getStoragesortCodeValue());
            medicineswapinfo.addChild(storage_condition);
        }

        //产地
        prod_place.setText(ymCMedicine.getOriginName());
        medicineswapinfo.addChild(prod_place);

        //英文名或拼音
        english_name.setText(ymCMedicine.getSpell());
        medicineswapinfo.addChild(english_name);


        //经营范围
        if("1".equals(ymCMedicine.getIsPrescription())) {
            scope_business.setText("处方药");
        } else {
            if("化学药".equals(ymCMedicine.getMedicType()))
                scope_business.setText("化学药制剂");
            else
                scope_business.setText(ymCMedicine.getMedicType());
        }
        medicineswapinfo.addChild(scope_business);

        //流通状态
        status.setText("4");
        medicineswapinfo.addChild(status);

        //存量
        is_old.setText("N");
        medicineswapinfo.addChild(is_old);

        //独家经营
        is_exc.setText("N");
        medicineswapinfo.addChild(is_exc);

        return medicineswapinfo;
    }

    private OMElement makeupXmlConvert(YmCMedicine ymCMedicine) {
        OMElement makeupswapinfo = fac.createOMElement("MAKEUPSWAPINFO", null);
        OMElement product_code = fac.createOMElement("PRODUCT_CODE", null);
        OMElement product_name = fac.createOMElement("PRODUCT_NAME", null);
        OMElement license_numbe = fac.createOMElement("LICENSE_NUMBE", null);
        OMElement corp_name = fac.createOMElement("CORP_NAME", null);
        OMElement is_import = fac.createOMElement("IS_IMPORT", null);
        OMElement approval_number = fac.createOMElement("APPROVAL_NUMBER", null);
        OMElement useful_life = fac.createOMElement("USEFUL_LIFE", null);
        OMElement pack_spec = fac.createOMElement("PACK_SPEC", null);
        OMElement first_code = fac.createOMElement("FIRST_CODE", null);
        OMElement sec_code = fac.createOMElement("SEC_CODE", null);
        OMElement prod_place = fac.createOMElement("PROD_PLACE", null);
        OMElement base_unit = fac.createOMElement("BASE_UNIT", null);
        OMElement scope_business = fac.createOMElement("SCOPE_BUSINESS", null);
        OMElement status = fac.createOMElement("STATUS", null);
        OMElement is_old = fac.createOMElement("IS_OLD", null);
        OMElement is_exc = fac.createOMElement("IS_EXC", null);


        product_code.setText(String.valueOf(ymCMedicine.getId()));
        makeupswapinfo.addChild(product_code);

        //通用名称
        if(ymCMedicine.getDefaultName().indexOf('#') == 0) {
            product_name.setText(ymCMedicine.getDefaultName().substring(1));
            makeupswapinfo.addChild(product_name);
        } else {
            product_name.setText(ymCMedicine.getDefaultName());
            makeupswapinfo.addChild(product_name);
        }

        //批准文号和进口注册证号
        if("0".equals(ymCMedicine.getIsImport()) || ymCMedicine.getIsImport() == null) {
            //非进口药品要填批准文号
            license_numbe.setText(ymCMedicine.getLicenseNumber());
            makeupswapinfo.addChild(license_numbe);
        } else if("1".equals(ymCMedicine.getIsImport())) {
            //进口药品要填进口注册证号
            approval_number.setText(ymCMedicine.getImportRegeditId());
            makeupswapinfo.addChild(approval_number);
        }


        //生产企业
        corp_name.setText(ymCMedicine.getFacName());
        makeupswapinfo.addChild(corp_name);

        //是否为进口产品
        is_import.setText(ymCMedicine.getIsImport());
        makeupswapinfo.addChild(is_import);


        //有效期（月）
        useful_life.setText(ymCMedicine.getPeriod());
        makeupswapinfo.addChild(useful_life);

        //一级分类 附1.1
        if("化学药".equals(ymCMedicine.getMedicType()) || "中成药".equals(ymCMedicine.getMedicType()) || "中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
            first_code.setText("1");
        }
        else if("非药品".equals(ymCMedicine.getMedicType()) && ("化妆品".equals(ymCMedicine.getOtcCode()))) {
            first_code.setText("2");
        }
        else if("保健食品".equals(ymCMedicine.getMedicType())) {
            first_code.setText("3");
        }
        else if("医疗器械".equals(ymCMedicine.getMedicType())) {
            first_code.setText("4");
        }

        makeupswapinfo.addChild(first_code);

        //二级分类 附1.2
        if("化学药".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("1");
        }
        else if("中成药".equals(ymCMedicine.getMedicType()) ) {
            sec_code.setText("2");
        }
        else if("中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("3");
        }
        else if("保健食品".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("8");
        }
        else if("非药品".equals(ymCMedicine.getMedicType()) && ("化妆品".equals(ymCMedicine.getOtcCode()))) {
            sec_code.setText("13");
        }
        else if("医疗器械".equals(ymCMedicine.getMedicType())) {
            if("一类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("15");
            } else if ("二类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("16");
            } else if ("三类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("17");
            } else {
                sec_code.setText("15");
            }
        }

        makeupswapinfo.addChild(sec_code);


        //包装规格
        pack_spec.setText(ymCMedicine.getStandard());
        makeupswapinfo.addChild(pack_spec);

        //单位 附1.4
        if(ymCMedicine.getBaseUnit() == null) {
            base_unit.setText("12");
        } else {
            List<YmSDic> list4 = dictionaryMapper.queryDicListExactly(ymCMedicine.getBaseUnit(), "单位");
            if (list4.size() != 0) {
                base_unit.setText(list4.get(0).getValue());
            } else {
                base_unit.setText("12");
            }
        }
        makeupswapinfo.addChild(base_unit);


        //产地
        prod_place.setText(ymCMedicine.getOriginName());
        makeupswapinfo.addChild(prod_place);


        //经营范围
        if("1".equals(ymCMedicine.getIsPrescription())) {
            scope_business.setText("处方药");
        } else {
            scope_business.setText(ymCMedicine.getMedicType());
        }
        makeupswapinfo.addChild(scope_business);

        //流通状态
        status.setText("4");
        makeupswapinfo.addChild(status);

        //存量
        is_old.setText("N");
        makeupswapinfo.addChild(is_old);

        //独家经营
        is_exc.setText("N");
        makeupswapinfo.addChild(is_exc);

        return makeupswapinfo;
    }
    private OMElement instrumentXmlConvert(YmCMedicine ymCMedicine) {
        OMElement instrumentswapinfo = fac.createOMElement("INSTRUMENTSWAPINFO", null);
        OMElement product_code = fac.createOMElement("PRODUCT_CODE", null);
        OMElement product_name = fac.createOMElement("PRODUCT_NAME", null);
        OMElement license_personname = fac.createOMElement("LICENSE_PERSONNAME", null);

        OMElement license_num_in = fac.createOMElement("LICENSE_NUM_IN", null);
        OMElement is_import = fac.createOMElement("IS_IMPORT", null);
        OMElement license_num_ex = fac.createOMElement("LICENSE_NUM_EX", null);
        OMElement spec = fac.createOMElement("SPEC", null);

        OMElement useful_life = fac.createOMElement("USEFUL_LIFE", null);
        OMElement pack_spec = fac.createOMElement("PACK_SPEC", null);
        OMElement base_unit = fac.createOMElement("BASE_UNIT", null);
        OMElement first_code = fac.createOMElement("FIRST_CODE", null);
        OMElement sec_code = fac.createOMElement("SEC_CODE", null);
        OMElement prod_place = fac.createOMElement("PROD_PLACE", null);
        OMElement english_name = fac.createOMElement("ENGLISH_NAME", null);
        OMElement scope_business = fac.createOMElement("SCOPE_BUSINESS", null);
        OMElement status = fac.createOMElement("STATUS", null);
        OMElement is_old = fac.createOMElement("IS_OLD", null);
        OMElement is_exc = fac.createOMElement("IS_EXC", null);


        product_code.setText(String.valueOf(ymCMedicine.getId()));
        instrumentswapinfo.addChild(product_code);

        //通用名称
        if(ymCMedicine.getDefaultName().indexOf('#') == 0){
            product_name.setText(ymCMedicine.getDefaultName().substring(1));
            instrumentswapinfo.addChild(product_name);
        } else {
            product_name.setText(ymCMedicine.getDefaultName());
            instrumentswapinfo.addChild(product_name);
        }

        //注册人名称
        license_personname.setText("0");
        instrumentswapinfo.addChild(license_personname);

        //批准文号和进口注册证号
        if("0".equals(ymCMedicine.getIsImport()) || ymCMedicine.getIsImport() == null) {
            //非进口药品要填批准文号
            license_num_in.setText(ymCMedicine.getLicenseNumber());
            instrumentswapinfo.addChild(license_num_in);
        } else if("1".equals(ymCMedicine.getIsImport())) {
            //进口药品要填进口注册证号
            license_num_ex.setText(ymCMedicine.getImportRegeditId());
            instrumentswapinfo.addChild(license_num_ex);
        }

        //规格
        spec.setText(ymCMedicine.getStandard());
        instrumentswapinfo.addChild(spec);


        //是否为进口产品
        is_import.setText(ymCMedicine.getIsImport());
        instrumentswapinfo.addChild(is_import);


        //有效期（月）
        useful_life.setText(ymCMedicine.getPeriod());
        instrumentswapinfo.addChild(useful_life);

        //一级分类 附1.1
        if("化学药".equals(ymCMedicine.getMedicType()) || "中成药".equals(ymCMedicine.getMedicType()) || "中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
            first_code.setText("1");
        }
        else if("非药品".equals(ymCMedicine.getMedicType()) && ("化妆品".equals(ymCMedicine.getOtcCode()))) {
            first_code.setText("2");
        }
        else if("保健食品".equals(ymCMedicine.getMedicType())) {
            first_code.setText("3");
        }
        else if("医疗器械".equals(ymCMedicine.getMedicType())) {
            first_code.setText("4");
        }

        instrumentswapinfo.addChild(first_code);

        //二级分类 附1.2
        if("化学药".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("1");
        }
        else if("中成药".equals(ymCMedicine.getMedicType()) ) {
            sec_code.setText("2");
        }
        else if("中药材（中药饮片）".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("3");
        }
        else if("保健食品".equals(ymCMedicine.getMedicType())) {
            sec_code.setText("8");
        }
        else if("非药品".equals(ymCMedicine.getMedicType()) && ("化妆品".equals(ymCMedicine.getOtcCode()))) {
            sec_code.setText("13");
        }
        else if("医疗器械".equals(ymCMedicine.getMedicType())) {
            if("一类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("15");
            } else if ("二类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("16");
            } else if ("三类医疗器械".equals(ymCMedicine.getOtcCode())) {
                sec_code.setText("17");
            } else {
                sec_code.setText("15");
            }
        }

        instrumentswapinfo.addChild(sec_code);


        //包装规格
        pack_spec.setText(ymCMedicine.getStandard());
        instrumentswapinfo.addChild(pack_spec);

        //单位 附1.4
        if(ymCMedicine.getBaseUnit() == null) {
            base_unit.setText("12");
        } else {
            List<YmSDic> list4 = dictionaryMapper.queryDicListExactly(ymCMedicine.getBaseUnit(), "单位");
            if (list4.size() != 0) {
                base_unit.setText(list4.get(0).getValue());
            } else {
                base_unit.setText("12");
            }
        }
        instrumentswapinfo.addChild(base_unit);

        //产地
        prod_place.setText(ymCMedicine.getOriginName());
        instrumentswapinfo.addChild(prod_place);

        //英文名或拼音
        english_name.setText(ymCMedicine.getSpell());
        instrumentswapinfo.addChild(english_name);

        //经营范围
        if("1".equals(ymCMedicine.getIsPrescription())) {
            scope_business.setText("处方药");
        } else {
            scope_business.setText(ymCMedicine.getMedicType());
        }
        instrumentswapinfo.addChild(scope_business);

        //流通状态
        status.setText("4");
        instrumentswapinfo.addChild(status);

        //存量
        is_old.setText("N");
        instrumentswapinfo.addChild(is_old);

        //独家经营
        is_exc.setText("N");
        instrumentswapinfo.addChild(is_exc);

        return instrumentswapinfo;
    }

    private File writeFile(String upload, String type, String orgCode, String token) {
        File fileBackUp = new File(System.getProperty("user.dir" ) + File.separator + "upload" + File.separator + "backup" + File.separator + "upload " + df.format(new Date()) + " " + orgCode + " " + type + " " + token + ".xml");
        if(!fileBackUp.getParentFile().exists()){
            fileBackUp.getParentFile().mkdirs();
        }
        try {
            Writer outBackUp = new FileWriter(fileBackUp);
            outBackUp.write(upload.toString());
            outBackUp.close();
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
        }
        return fileBackUp;
    }
    private File writeFileParts(String upload, String type, String orgCode, int parts) {
        File fileBackUp = new File(System.getProperty("user.dir" ) + File.separator + "upload" + File.separator + "backup" + File.separator + "upload " + df.format(new Date()) + " " + orgCode + " " + type + " parts-" + String.valueOf(parts) + ".xml");
        if(!fileBackUp.getParentFile().exists()){
            fileBackUp.getParentFile().mkdirs();
        }
        try {
            Writer outBackUp = new FileWriter(fileBackUp);
            outBackUp.write(upload.toString());
            outBackUp.close();
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
        }
        return fileBackUp;
    }

    private String invokeSoapWsUpload(File file) {
        String url = wsdlUrl;
        Resume resume = new Resume();
        resume.setCandidateName(file.getName().substring(0, file.getName().lastIndexOf(".") - 1));
        resume.setResumeFileType("xml");
        DataSource source = new FileDataSource(file);
        resume.setResume(new DataHandler(source));
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(MasterDataWebService.class);
        factory.setAddress(url);
        MasterDataWebService client = (MasterDataWebService)factory.create();

        return client.uploadMasterData(resume);

    }

    private String invokeSoapWsFeedback(String xmlData) {
        String url = wsdlUrl;
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(MasterDataWebService.class);
        factory.setAddress(url);
        MasterDataWebService client = (MasterDataWebService)factory.create();
        return client.msgFeedback(xmlData);
    }

    private OMElement feedbackXmlConvert(String resultSeq) {
        OMElement upload = fac.createOMElement("UPLOAD", null);
        OMElement type = fac.createOMElement("TYPE", null);
        OMElement resultSeqElement = fac.createOMElement("RESULTSEQ", null);

        type.setText("1");
        resultSeqElement.setText(resultSeq);

        upload.addChild(type);
        upload.addChild(resultSeqElement);

        return upload;
    }

    private void uploadXml(OMElement upload, OMElement uploadType, int num, String orgCode, String type, int part, String token){
        log.info(type);
        log.info(String.valueOf(num));
        if(num == 0) return;
        upload.addChild(uploadType);
        String response = null;
        if(part > 0) {
            response = invokeSoapWsUpload(writeFileParts(upload.toString(), type, orgCode, part));
        } else {
            response = invokeSoapWsUpload(writeFile(upload.toString(), type, orgCode, token));
        }
        if(response.contains("成功"))
            log.info(response);
        else
            log.error(orgCode + df.format(new Date()) + type +"上传失败");
    }
}
